"""
主页相关路由
"""
from flask import Blueprint, render_template, request
from flask_login import login_required, current_user
from app.services import DashboardService, ProjectService
from datetime import datetime, timedelta

# 创建蓝图
main_bp = Blueprint('main', __name__)

@main_bp.route('/')
@login_required
def home():
    """首页 - 工作台"""
    # 获取工作台所需的数据
    from app.services import DashboardService
    from app.models import Project, ProjectTask, Customer, User, get_db
    
    db = get_db()
    
    # 获取基本统计数据
    stats = {
        'project_count': Project.query.filter_by(manager_id=current_user.id).count(),
        'my_tasks_count': ProjectTask.query.filter_by(assignee_id=current_user.id).count(),
        'customer_count': Customer.query.filter_by(manager_id=current_user.id).count(),
        'completed_tasks': ProjectTask.query.filter_by(assignee_id=current_user.id, status='completed').count(),
        'pending_tasks': ProjectTask.query.filter_by(assignee_id=current_user.id, status='pending').count(),
        'active_projects': Project.query.filter_by(manager_id=current_user.id, status='in-progress').count(),
        'new_customers_month': Customer.query.filter_by(manager_id=current_user.id).count(),  # 简化处理
        'monthly_hours': 160,  # 模拟数据
        'weekly_hours': 40     # 模拟数据
    }
    
    # 获取我的任务
    my_tasks = ProjectTask.query.filter_by(assignee_id=current_user.id).limit(8).all()
    
    # 获取项目进度
    projects = Project.query.filter_by(manager_id=current_user.id).limit(6).all()
    
    # 获取最近活动 - 使用空列表代替，因为没有Activity模型
    activities = []
    
    return render_template('home.html', 
                         stats=stats, 
                         my_tasks=my_tasks, 
                         projects=projects, 
                         activities=activities)

@main_bp.route('/dashboard')
@login_required
def dashboard():
    """仪表板"""
    dashboard_data = DashboardService.get_dashboard_stats()
    return render_template('dashboard.html', **dashboard_data)

@main_bp.route('/progress/tracking')
@login_required
def progress_tracking():
    """进度跟踪页面"""
    # 获取项目ID参数（可选）
    project_id = request.args.get('project_id', type=int)
    
    # 获取当前用户的所有项目
    from app.models import Project, ProjectMilestone
    from app import db
    
    # 获取项目统计数据
    projects = Project.query.filter_by(manager_id=current_user.id).all()
    total_projects = len(projects)
    completed_projects = len([p for p in projects if p.status == 'completed'])
    at_risk_projects = len([p for p in projects if p.status in ['delayed', 'at_risk']])
    
    # 获取即将到来的里程碑（未来30天内）
    upcoming_milestones = []
    today = datetime.now().date()
    thirty_days_later = today + timedelta(days=30)
    
    for project in projects:
        milestones = ProjectMilestone.query.filter_by(project_id=project.id).all()
        for milestone in milestones:
            if milestone.due_date and today <= milestone.due_date <= thirty_days_later:
                days_remaining = (milestone.due_date - today).days
                upcoming_milestones.append({
                    'name': milestone.name,
                    'project_id': project.id,
                    'project_name': project.name,
                    'days_remaining': days_remaining
                })
    
    # 获取最近的周报数据（模拟数据）
    recent_reports = []
    for project in projects[:3]:  # 只显示前3个项目
        recent_reports.append({
            'week_start_date': (today - timedelta(days=7)).strftime('%Y-%m-%d'),
            'week_end_date': (today - timedelta(days=1)).strftime('%Y-%m-%d'),
            'user_name': current_user.name,
            'project_id': project.id,
            'project_name': project.name,
            'weekly_work_hours': 40,
            'weekly_work_content': '项目开发和测试工作'
        })
    
    # 构建仪表板数据
    dashboard_data = {
        'my_projects': total_projects,
        'completed_projects': completed_projects,
        'total_projects': total_projects,
        'at_risk_projects': at_risk_projects,
        'upcoming_milestones': upcoming_milestones,
        'recent_reports': recent_reports
    }
    
    # 如果有指定项目ID，获取该项目的特定数据
    selected_project = None
    if project_id:
        selected_project = Project.query.get(project_id)
        if selected_project and selected_project.manager_id != current_user.id:
            selected_project = None  # 权限检查
    
    return render_template('progress_tracking.html', 
                         dashboard_data=dashboard_data,
                         projects=projects,
                         selected_project=selected_project,
                         today_date=datetime.now().strftime('%Y-%m-%d'))